<template>
  <div class="reopen-claim-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>重开赔案审核列表</h1>
    </div>

    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" size="default">
        <el-form-item label="报案号" prop="reportNo">
          <el-input
              v-model="searchForm.reportNo"
              placeholder="请输入报案号"
              clearable
              style="width: 220px;"
              maxlength="32"
          ></el-input>
        </el-form-item>

        <el-form-item label="保单编号" prop="policyId">
          <el-input
              v-model="searchForm.policyId"
              placeholder="请输入保单编号"
              clearable
              style="width: 220px;"
              maxlength="32"
          ></el-input>
        </el-form-item>

        <el-form-item label="审核状态" prop="approveStatus">
          <el-select
              v-model="searchForm.approveStatus"
              placeholder="请选择审核状态"
              clearable
              style="width: 220px;"
          >
            <el-option label="待审核" value="1"></el-option>
            <el-option label="已通过" value="2"></el-option>
            <el-option label="已驳回" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm" style="margin-left: 8px;">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
          :data="tableData"
          border
          stripe
          v-loading="loading"
          element-loading-text="正在加载数据..."
          style="width: 100%;"
          size="small"
      >
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column prop="reopenId" label="重开ID" width="100" align="center"></el-table-column>
        <el-table-column prop="reportNo" label="报案号" width="180" align="center"></el-table-column>
        <el-table-column prop="policyId" label="保单编号" width="160" align="center"></el-table-column>
        <el-table-column prop="applicant" label="申请人" width="120" align="center"></el-table-column>
        <el-table-column
            prop="applyTime"
            label="申请时间"
            width="180"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="reopenMoney"
            label="重开金额(元)"
            width="140"
            align="center"
        ></el-table-column>
        <!-- 审核状态列：用el-tag渲染，解决显示问题 -->
        <el-table-column label="审核状态" width="120" align="center">
          <template #default="scope">
            <el-tag
                :type="getTagType(scope.row.approveStatus)"
                effect="dark"
                size="small"
            >
              {{ getApproveStatusText(scope.row.approveStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleView(scope.row)">查看详情</el-button>
            <el-button
                size="small"
                type="success"
                @click="handleAudit(scope.row)"
                style="margin-left: 8px;"
                v-if="scope.row.approveStatus === 1"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            size="small"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 查看详情弹窗 -->
    <el-dialog
        title="重开赔案详情"
        v-model="detailDialogVisible"
        width="600px"
        :before-close="handleDetailDialogClose"
        destroy-on-close
    >
      <el-form
          :model="detailForm"
          label-width="140px"
          size="default"
          class="detail-form"
      >
        <el-form-item label="报案号">
          <el-input v-model="detailForm.reportNo" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="保单编号">
          <el-input v-model="detailForm.policyId" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="申请人">
          <el-input v-model="detailForm.applicant" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-input v-model="detailForm.applyTime" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="重开金额(元)">
          <el-input v-model="detailForm.reopenMoney" disabled placeholder="0.00"></el-input>
        </el-form-item>
        <el-form-item label="重开原因">
          <el-input
              type="textarea"
              v-model="detailForm.reopenReason"
              disabled
              rows="4"
              placeholder="无"
          ></el-input>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-tag
              :type="getTagType(detailForm.approveStatus)"
              effect="dark"
              size="small"
              disabled
          >
            {{ detailForm.approveStatusText }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核备注" v-if="detailForm.approveStatus !== 1">
          <el-input
              type="textarea"
              v-model="detailForm.approveRemark"
              disabled
              rows="2"
              placeholder="无"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleDetailDialogClose">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog
        title="审核操作"
        v-model="approveDialogVisible"
        width="500px"
        :before-close="handleApproveDialogClose"
    >
      <el-form
          ref="approveFormRef"
          :model="approveForm"
          :rules="approveFormRules"
          label-width="120px"
          size="default"
      >
        <el-form-item label="报案号">
          <el-input v-model="approveForm.reportNo" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item label="保单编号">
          <el-input v-model="approveForm.policyId" disabled placeholder="无"></el-input>
        </el-form-item>
        <el-form-item
            label="审核员"
            prop="approveUser"
            required
        >
          <el-select
              v-model="approveForm.approveUser"
              placeholder="请选择审核员"
              :loading="auditorLoading"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="auditor in auditorList"
                :key="auditor.workNo"
                :label="`${auditor.realName} (${auditor.workNo})`"
                :value="auditor.workNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item
            label="审核状态"
            prop="approveStatus"
            required
        >
          <el-select
              v-model="approveForm.approveStatus"
              placeholder="请选择审核状态"
              clearable
          >
            <el-option label="已通过" value="2"></el-option>
            <el-option label="已驳回" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
            label="审核备注"
            prop="approveRemark"
            :required="approveForm.approveStatus === '3'"
        >
          <el-input
              v-model="approveForm.approveRemark"
              type="textarea"
              rows="4"
              placeholder="请输入审核备注（驳回时必填）"
              maxlength="500"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleApproveDialogClose">取消</el-button>
        <el-button
            type="primary"
            @click="submitApproveForm"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import hxxp from '@/utils/hxxp';

// 1. 核心状态管理
const loading = ref(false);               // 表格加载状态
const tableData = ref([]);               // 表格数据源
const detailDialogVisible = ref(false);  // 查看详情弹窗显示状态
const approveDialogVisible = ref(false); // 审核弹窗显示状态
const approveFormRef = ref(null);        // 审核表单引用

// 审核员数据
const auditorList = ref([]);             // 审核员列表
const auditorLoading = ref(false);       // 审核员数据加载状态

// 2. 当前操作的重开ID
const currentReopenId = ref('');

// 3. 查询表单数据
const searchForm = reactive({
  reportNo: '',        // 报案号
  policyId: '',        // 保单编号
  approveStatus: ''    // 审核状态：1-待审核，2-已通过，3-已驳回
});

// 4. 分页配置（与后端返回结构对齐）
const pagination = reactive({
  pageNum: 1,    // 当前页码
  pageSize: 5,   // 每页条数
  total: 0       // 总记录数
});

// 5. 详情表单数据（匹配后端返回字段）
const detailForm = reactive({
  reopenId: '',
  reportNo: '',
  applicant: '',
  applyTime: '',
  policyId: '',
  reopenReason: '',
  reopenMoney: '',
  approveStatus: '',
  approveStatusText: '',
  approveRemark: ''
});

// 6. 审核表单数据
const approveForm = reactive({
  reopenId: '',
  reportNo: '',
  policyId: '',
  approveStatus: '', // 2=通过，3=驳回
  approveRemark: '',
  approveUser: ''      // 审核员ID
});

// 7. 审核表单校验规则
const approveFormRules = reactive({
  approveStatus: [
    { required: true, message: '请选择审核状态', trigger: 'change' }
  ],
  approveUser: [
    { required: true, message: '请选择审核员', trigger: 'change' }
  ],
  approveRemark: [
    { required: () => approveForm.approveStatus === '3', message: '驳回时必须填写审核备注', trigger: 'blur' },
    { max: 500, message: '审核备注不能超过500个字符', trigger: 'blur' }
  ]
});

// 8. 页面挂载时加载数据
onMounted(() => {
  fetchReopenList();
  fetchAuditorList();
});

// 9. 核心方法：获取重开赔案列表（对接后端接口）
const fetchReopenList = async () => {
  loading.value = true;
  try {
    const response = await hxxp.get('/aiClaimReopen/reopenList', {
      params: {
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
        policyId: searchForm.policyId || undefined,
        reportNo: searchForm.reportNo || undefined,
        approveStatus: searchForm.approveStatus || undefined
      }
    });

    // 解析后端返回结构（匹配用户提供的格式）
    if (response.code === 100200 && response.data.code === 100200) {
      const result = response.data.data;
      // 兼容后端返回的数组或分页对象
      if (Array.isArray(result)) {
        tableData.value = result;
        pagination.total = result.length;
      } else {
        tableData.value = result.list || [];
        pagination.total = result.total || 0;
        pagination.pageNum = result.pageNum || 1;
        pagination.pageSize = result.pageSize || 5;
      }
    } else {
      ElMessage.error(`获取数据失败：${response.data.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取重开赔案列表异常：', error);
    
    // 详细的错误信息处理
    if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接或后端服务状态');
    } else if (error.response) {
      // 服务器响应了错误状态码
      ElMessage.error(`服务器错误：${error.response.status} - ${error.response.statusText}`);
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('网络连接失败，请检查后端服务是否启动（端口9000）');
    } else {
      // 其他错误
      ElMessage.error(`请求失败：${error.message}`);
    }
  } finally {
    loading.value = false;
  }
};

/**
 * 获取审核员列表数据
 */
const fetchAuditorList = async () => {
  auditorLoading.value = true;
  try {
    const response = await hxxp.get('/aiStaffUser/worker', {
      params: {
        positionCode: 'PTN001'
      }
    });
    
    if (response.code === 100200) {
      auditorList.value = response.data || [];
      console.log('审核员列表数据:', auditorList.value);
    } else {
      ElMessage.error(`获取审核员列表失败：${response.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取审核员列表异常：', error);
    ElMessage.error('网络异常，获取审核员列表失败，请稍后重试');
  } finally {
    auditorLoading.value = false;
  }
};

// 10. 工具方法：获取审核状态文本（数字转中文）
const getApproveStatusText = (status) => {
  const statusMap = {
    '1': '待审核',
    '2': '已通过',
    '3': '已驳回'
  };
  // 处理状态为数字或字符串的情况
  const statusStr = String(status);
  return statusMap[statusStr] || '未知状态';
};

// 11. 工具方法：获取审核状态标签类型（匹配Element Plus Tag组件）
const getTagType = (status) => {
  const typeMap = {
    '1': 'warning',  // 橙色：待审核
    '2': 'success',  // 绿色：已通过
    '3': 'danger'    // 红色：已驳回
  };
  const statusStr = String(status);
  return typeMap[statusStr] || 'info';
};

// 12. 查询操作：执行查询
const handleSearch = () => {
  pagination.pageNum = 1;  // 重置到第一页
  fetchReopenList();
};

// 13. 查询操作：重置查询条件
const resetForm = () => {
  searchForm.reportNo = '';
  searchForm.policyId = '';
  searchForm.approveStatus = '';
  pagination.pageNum = 1;
  fetchReopenList();
};

// 14. 分页操作：每页条数改变
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchReopenList();
};

// 15. 分页操作：当前页码改变
const handleCurrentChange = (val) => {
  pagination.pageNum = val;
  fetchReopenList();
};

// 16. 查看详情：打开弹窗并填充数据
const handleView = (row) => {
  // 清空表单
  Object.keys(detailForm).forEach(key => {
    detailForm[key] = '';
  });

  // 填充数据（兼容后端字段可能为null/undefined的情况）
  detailForm.reopenId = row.reopenId || '';
  detailForm.reportNo = row.reportNo || '';
  detailForm.policyId = row.policyId || '';
  detailForm.applicant = row.applicant || '';
  detailForm.applyTime = row.applyTime || '';
  detailForm.reopenReason = row.reopenReason || '无';
  detailForm.reopenMoney = row.reopenMoney || '0.00';
  detailForm.approveStatus = row.approveStatus || '';
  detailForm.approveStatusText = getApproveStatusText(row.approveStatus);
  detailForm.approveRemark = row.approveRemark || '无';

  // 显示弹窗
  detailDialogVisible.value = true;
};

// 17. 查看详情：关闭弹窗
const handleDetailDialogClose = () => {
  detailDialogVisible.value = false;
};

// 18. 审核操作：打开审核弹窗
const handleAudit = (row) => {
  currentReopenId.value = row.reopenId;
  // 填充基础数据
  approveForm.reopenId = row.reopenId;
  approveForm.reportNo = row.reportNo || '';
  approveForm.policyId = row.policyId || '';
  approveForm.approveStatus = ''; // 重置审核状态
  approveForm.approveRemark = ''; // 清空备注
  approveForm.approveUser = '';     // 重置审核员

  approveDialogVisible.value = true;
};

// 19. 审核操作：关闭审核弹窗
const handleApproveDialogClose = () => {
  if (approveFormRef.value) {
    approveFormRef.value.resetFields();
  }
  approveDialogVisible.value = false;
};

// 20. 审核操作：提交审核结果
const submitApproveForm = async () => {
  // 表单校验
  const validatePass = await new Promise((resolve) => {
    approveFormRef.value.validate((isValid) => {
      resolve(isValid);
    });
  });
  if (!validatePass) return;

  try {
    loading.value = true;

    // 构建提交数据（匹配后端接口要求）
    const submitData = {
      reopenId: approveForm.reopenId,
      reportNo: approveForm.reportNo,
      policyId: approveForm.policyId,
      approveStatus: Number(approveForm.approveStatus), // 转为数字类型
      approveRemark: approveForm.approveRemark || '',
      approveUser: approveForm.approveUser // 审核员ID，对应数据库字段approveUser
    };

    console.log('提交的审核数据：', submitData);
    // 调用PUT接口提交审核结果
    const response = await hxxp.put('/aiClaimReopen/updateReopen', submitData);
    if (response.code === 100200) {
      ElMessage.success('审核操作保存成功');
      handleApproveDialogClose();
      fetchReopenList(); // 刷新列表
    } else {
      ElMessage.error(`操作失败：${response.data.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('提交审核结果异常：', error);
    
    // 详细的错误信息处理
    if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接');
    } else if (error.response) {
      ElMessage.error(`服务器错误：${error.response.status} - ${error.response.statusText}`);
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查后端服务状态');
    } else {
      ElMessage.error(`操作失败：${error.message}`);
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 全局容器样式 */
.reopen-claim-container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 20px;
}
.page-header h1 {
  font-size: 18px;
  color: #1f2329;
  margin: 0;
  font-weight: 600;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 4px;
}
.search-form {
  padding: 16px 0;
}

/* 表格卡片样式 */
.table-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-radius: 4px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 12px;
  text-align: right;
}

/* 详情表单样式 */
.detail-form {
  margin-top: 10px;
}
.detail-form .el-form-item {
  margin-bottom: 12px;
}

/* 表格单元格溢出处理 */
::v-deep .el-table__cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 弹窗样式补充 */
::v-deep .el-dialog__body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

/* 标签样式微调 */
::v-deep .el-tag--small {
  padding: 2px 8px;
  font-size: 12px;
}
</style>